package org.room402.framework.chat.container;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import org.room402.constant.system.ErrorCode;
import org.room402.entity.chat.UserSession;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketSession;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class UserSessionContext {
    private final ConcurrentHashMap<String, UserSession> sidToUser = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, UserSession> uidToUser = new ConcurrentHashMap<>();

    private final AtomicInteger idPool = new AtomicInteger();

    /**
     * 删除用户
     */
    public UserSession removeBySid(String sid) {
        UserSession userSession = sidToUser.remove(sid);
        uidToUser.remove(userSession.getId());
        return userSession;
    }

    public UserSession removeByUid(String uid) {
        UserSession userSession = uidToUser.remove(uid);
        uidToUser.remove(userSession.getSession().getId());
        return userSession;
    }

    /**
     * 用户注册
     */
    public UserSession register(WebSocketSession session, JSONObject object) {
        UserSession userSession = UserSession.form(session, object, getId());
        pushUser(userSession);
        return userSession;
    }

    /**
     * 用户添加
     */
    private void pushUser(UserSession userSession) {
        sidToUser.put(userSession.getSession().getId(), userSession);
        uidToUser.put(userSession.getId(), userSession);
    }

    /**
     * 通过sessionID获取用户
     */
    public UserSession getBySid(String sid) {
        return sidToUser.get(sid);
    }

    public UserSession validBySid(String sid) {
        UserSession bySid = getBySid(sid);
        if (Objects.isNull(bySid)) {
            ErrorCode.USER_NOT_FOUND.throwException();
        }
        return bySid;
    }

    public UserSession validByUid(String targetId) {
        UserSession byUid = getByUid(targetId);
        if (Objects.isNull(byUid)) {
            ErrorCode.USER_NOT_FOUND.throwException();
        }
        return byUid;
    }

    /**
     * 通过用户ID获取用户
     */
    public UserSession getByUid(String uid) {
        return uidToUser.get(uid);
    }


    /**
     * 获得唯一ID
     */
    private String getId() {
        return StrUtil.fillBefore(String.valueOf(idPool.incrementAndGet()), '0', 4);
    }


}
